package com.qf.rbac.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.rbac.sys.entity.SysUserRole;
import com.qf.rbac.sys.mapper.SysUserRoleMapper;
import com.qf.rbac.sys.service.ISysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户与角色对应关系 服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2022-04-16
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    @Override
    public void saveOrUpdate(Long userId, List<Long> roleIdList) {
        //先删除用户与角色关系
        this.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));

        if(roleIdList == null || roleIdList.size() == 0){
            return ;
        }

        //保存用户与角色关系
        for(Long roleId : roleIdList){
            SysUserRole sysUserRoleEntity = new SysUserRole();
            sysUserRoleEntity.setUserId(userId);
            sysUserRoleEntity.setRoleId(roleId);

            this.save(sysUserRoleEntity);
        }

    }

    @Override
    public List<Long> queryRoleIdList(Long userId) {

        List<SysUserRole> list = this.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,userId));
        List<Long> collect = list.stream().map(sysUserRole -> sysUserRole.getRoleId()).collect(Collectors.toList());

        return collect;
    }
}
